package com.cellulam.framework.fs.excel.utils;

import com.cellulam.framework.fs.common.DataTable;
import com.cellulam.framework.fs.excel.model.ExcelFieldMeta;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
public abstract class DataTableUtils {

    /**
     * 从数据集合中, 构建DataTable
     *
     * @param rows
     * @param excelClass
     * @return
     */
    public static DataTable build(List<?> rows, Class<?> excelClass) {
        List<ExcelFieldMeta> fields = ExcelMetaUtils.readExcelProperty(excelClass);
        DataTable dt = new DataTable();

        fields.forEach(f -> dt.addHeader(f.getTitle()));

        if (CollectionUtils.isNotEmpty(rows)) {
            rows.forEach(row -> {
                List<Object> rowValues =
                        fields.stream().map(f -> {
                            try {
                                Object fValue = f.getRawField().get(row);
                                return fValue;
                            } catch (IllegalAccessException e) {
                                throw new RuntimeException("get field#{} from object error", e);
                            }
                        }).collect(Collectors.toList());
                dt.addRow(rowValues);
            });
        }

        return dt;
    }

}
